<template>
	<view class="container">
		<view class="iner">基本信息</view>
		<view class="headerNumber" @click="handleProducts">
			<view style="font-size: 24rpx;">生产单号</view>
			<view style="font-size: 26rpx;color: #999999 ;">{{model.no || '请选择生产单号'}} ></view>
		</view>
		<view class="iners" v-if="materials.length>0">
			<span>回退料品(共</span>
			<span>{{materials.length}}</span>
			<span>个种类)</span>
		</view>
		<view class="material" v-if="materials.length>0">
			<!-- 主要原料 -->
			<view class="picking" >
				<view class="pickingTitles" style="margin-bottom: 20rpx;">
					<view class="flex">
						<span>主要原料：</span>
						<span style="color: #999999 ;">{{setMaterials() || '暂无'}}</span>
					</view>
					<image @click="handeleAddMaterials" style="width: 34rpx;height: 34rpx;" src="/static/work/cg_add03.png"
						mode=""></image>
				</view>
				<!-- <view class="pickingTitle">
					<view class="flex" style="width: 250rpx;">
						<view>数量：</view>
						<view>2000kg</view>
					</view>
					<view class="flex" style="width: 300rpx;">
						<view>已领数量：</view>
						<view>2000kg</view>
					</view>
					<view class="flex" style="width: 300rpx;">
						<view>剩余可领：</view>
						<view>2000kg</view>
					</view>
				</view> -->
				<view class="selectBlock" v-for="(item,index) in materials" :key="index">
					<view class="select_top">
						<view>原料：{{item.productName}}</view>
						<view style="margin-left: 20rpx;">数量：{{item.itemsBatchVoList[0].totalCount}}</view>
					</view>
					<view class="handeleLibrary">
						<view class="select" @click="handeleLibrary(index)">
							<view v-if="item.name" class="lib">{{item.name}}</view>
							<view v-else style="color: #999999 ;">选货位</view>
							<image style="width: 16rpx;height: 16rpx;" src="/static/work/bottom.png" mode=""/>
						</view>
						
						<view class="selectActive">
							<input type="number" style="font-size: 24rpx;display: flex;align-items: center;" v-model="item.count"
								placeholder-style="font-size:24rpx;" placeholder="请输入数量" @input="handleTotal($event,index,item.productId)">
							<view style="font-size: 24rpx;">{{item.unitName}}</view>
						</view>
						<view class="selectImage" v-if="materials.length>1" @click="handeleRemoveMaterials(index)">
							<image style="width: 34rpx;height: 34rpx;" src="/static/work/cg_add04.png" mode=""/>
						</view>
					</view>
					
				</view>
			</view>
			<view class="submit">
				<u-button :loading='loading' :custom-style="customStyleBtn1" @click="submit">确认退料</u-button>
			</view>
			
		</view>
		
		 <u-picker :show="isShow" :columns="arrayList" keyName="productName" @confirm="handleIsShowproductName"></u-picker>
		<Warehouse @setValueName="handleSetValueName"  ref="warehouseRef"/>
	</view>
</template>

<script>
	import Warehouse from '@/components/Warehouse.vue'
	import {
		constructGroups
	} from '@/utils/common.js'
	
	import {getProductionReturnInfo,productionReturn,getWarehouse} from '@/api/store.js'
	export default {
		components:{
			Warehouse
		},
		data() {
			return {
				isShow:false,
				customStyleBtn1: {
					width: '690rpx',
					height: '90rpx',
					borderRadius: '45rpx',
					background: "linear-gradient(0deg, #177A77, #4B9C6D)",
					fontSize: '28rpx',
					fontWeight: 400,
					color: '#ffffff',
					border: 'none'
				},
				materials: [ ],//主原料
				columnslibrary: [],//仓库一级数据
				columnData: [],//仓库二级数据
				disabled:true,//按钮
				loading: false,//按钮
				libraryShow:false, //控制选择仓库弹窗
				hostIndex:0,//主选择ID
				assistIndex:0,//辅选择ID
				index:0,//选择主还是辅
				show: false,
				model:{},//
				backups:{},//备份数据
				productionOrderId:'',
				moneys:[],
				arrayList:[],//添加弹窗展示的商品
			}
		},
		onLoad() {
			this.handleCustomEventBind = this.handleCustomEvent.bind(this);
			uni.$on('materials', this.handleCustomEventBind);
		},
		methods: {
			// 获取仓库货位列表
			async getWarehouses() {
				let response = await getWarehouse()
				this.moneys = response.data.list
				const arr = response.data.list.map(item => {
					return {
						id: item.parentId ? null : item.id,
						name: item.name,
						parentId: item.parentId,
					}
				})
				let objs = constructGroups(arr)
				this.columnslibrary = objs.columns
				this.columnData = objs.columnData
			},
			// 库位选项
			handleSetValueName(val){
				this.materials[this.index].name = val.name
				this.materials[this.index].warehouseId = val.id
				console.log('materials:',this.materials);
			},
			// 确认领料
			async submit() {
				let bol = false
				for(const item of this.materials){
					if(!item.warehouseId){
						uni.showToast({
							title:'请选择货位',
							icon:'none'
						})
						bol = true
						break; // 找到目标，终止循环
					}
					if(!item.count){
						uni.showToast({
							title:'请输入数量',
							icon:'none'
						})
						bol = true
						break; // 找到目标，终止循环
					}
				}
				if (bol) return
				this.loading = true
				let data = {
					productionOrderId:this.productionOrderId,
					productionReturnItemsSaveReqVOList:this.materials.map(item=>{
						return{
							batchNumber:item.itemsBatchVoList[0].batchNumber, //批次号
							count:item.count,//数量
							productId:item.productId, //商品id
							warehouseId:item.warehouseId //货位
						}
					})
				}
				let res = await productionReturn(data)
				 uni.$off('materials', this.handleCustomEventBind);
				uni.showToast({
					title:'退回成功',
					icon:'none'
				})
				uni.navigateBack()
				
				this.loading = false
			},
			// 计算合计数量
			handleTotal(event, index, id) {
			    // 总数
			    let total = this.materials[index].Total;
			    // 获取匹配的商品数据
			    let arr = this.materials.filter(item => item.productId == id);
			    // 合计数量
			    const counts = arr.reduce((sum, product) => {
			        const count = Number(product.count);
			        return isNaN(count) ? sum : sum + count;  // 只有在 count 是有效数字时才加到 sum
			    }, 0);
			    // 获取用户输入的值
			    let inputValue = event.detail.value.trim();  // 去掉两边空格
			    // 检查输入值是否是有效数字
			    const inputNumber = Number(inputValue);
			    if (isNaN(inputNumber)) {
			        // 如果输入的不是有效数字，清空输入框或显示警告
			        this.materials[index].count = '';
			        return; // 提前返回，不进行后续逻辑
			    }
			    // 如果输入的数量大于总数，清空输入框
			    if (counts > total) {
					this.$nextTick(()=>{
						this.materials[index].count = '';
					})
			        uni.showToast({
			            title: '输入数量不能超过总数',
			            icon: 'none',
			            duration: 2000
			        });
			        return;
			    }
			    // 如果没有问题，将输入的数量更新到材料数据中
			    // this.materials[index].count = inputNumber;
			},
			// 选择仓库确定
			confirm(e){
				let b = this.moneys.filter(item => item.name == e.value[1])
				this.materials[this.index].warehouseId = b[0].id
				this.materials[this.index].name = b[0].name
				
				this.libraryShow = false
			},
			// 选择主仓库，或辅料仓库
			handeleLibrary(index,){
				this.$refs.warehouseRef.handleIsShow([],false)
				this.index = index
			},
			
			handleIsShowproductName(val) {
			    const product = val.value[0]; 
				 const products = val.value.map(item=>{
					 return{
						 ...item,
						 Total:item.itemsBatchVoList[0].totalCount
					 }
				 })
				console.log('val.value[0]:',val.value);
				 // 获取当前商品
			    const isProductExist = this.materials.some(item => item.productId === product.productId);  // 检查商品是否已经存在
			    if (product.itemsBatchVoList[0].totalCount == 1 && isProductExist) {
			        // 如果商品数量为1且商品已存在
			        uni.showToast({
			            title: '商品数量为1不需要添加新货位',
			            icon: 'none'
			        });
			        this.isShow = false;
			    } else {
			        // 否则将商品添加到materials数组中
					
			        this.materials.push(products[0]);
			        this.isShow = false;
			    }
			},
			// 增加主原料
			handeleAddMaterials() {
				this.isShow = true
				// this.materials.push(this.backups)
			},
			// 删除主原料
			handeleRemoveMaterials(index) {
				uni.showModal({
					title: '提示',
					content: '确认删除此条信息？',
					success: res => {
						if (res.confirm) {
							this.materials.splice(index, 1)
						}
					}
				});
			},
			
			
			// 跳转至生产单列表
			handleProducts(){
				uni.navigateTo({
					url:'/pages/work/produce/productionOrderList'
				})
			},
			setMaterials(){
				let items = JSON.parse(JSON.stringify(this.materials))
				const names = items.map(item => item.productName).join(", ");
				return names
			},
			// 返回的生产单信息，调接口获取原料
			async handleCustomEvent(val){
				this.productionOrderId = val.data.id
				this.model = val.data
				let res = await getProductionReturnInfo({id:val.data.id})
				
				if(res.data.length==0){
					uni.showToast({
						title:'该生产单没有能退料的产品',
						icon:'none'
					})
				}
				this.materials = res.data.map(item=>{
					return{
						...item,
						name:'',
						warehouseId:'',
						Total:item.itemsBatchVoList[0].totalCount
					}
				})
				this.arrayList= []
				// 添加商品选择
				let List = res.data.map(item=>{
					return{
						...item,
						name:'',
						warehouseId:'',
					}
				})
				this.arrayList.push(List)
				
				this.getWarehouses()
			}
		},
		onUnload(){
			uni.$off('materials')
		}
	}
</script>

<style scoped>
	.select_top{
		width: 100%;
		height: 80rpx;
		font-size: 24rpx;
		display: flex;
		align-items: center;
	}
	.handeleLibrary{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.lib{
		width: 140rpx;
		text-overflow: ellipsis;
		    overflow: hidden;
		    word-break: break-all;
		    white-space: nowrap;
	}
	.selectImage {
		width: 58rpx;
		height: 58rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.selectBlock {
		width: 100%;
		display: flex;
		flex-direction: column;
		/* align-items: center; */
		justify-content: space-between;
		margin-bottom: 18rpx;
	}
	
	.select {
		flex: 1;
		height: 60rpx;
		border: 1px solid #EBEBEB;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-right: 19rpx;
		padding: 0rpx 21rpx;
		box-sizing: border-box;
		font-size: 24rpx;
	}
	.selectActive {
		flex: 1;
		height: 60rpx;
		border: 1px solid #EBEBEB;
		display: flex;
		align-items: center;
		padding: 0 21rpx;
		box-sizing: border-box;
	}
	
	.pickingTitles {
		font-size: 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.flex {
		display: flex;
		align-items: center;
	}
	
	.pickingTitle {
		font-size: 24rpx;
		margin-bottom: 30rpx;
		display: flex;
		align-items: center;
	}
	.pickingActive {
		width: 750rpx;
		min-height: 200rpx;
		background-color: #FFFFFF;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
	}
	.picking {
		width: 750rpx;
		min-height: 200rpx;
		background-color: #FFFFFF;
		padding: 0rpx 30rpx 21rpx 30rpx;
		box-sizing: border-box;
	}
	.submit {
		width: 100%;
		position: relative;
		margin-top: 97rpx;
		margin-bottom: 100rpx;
	}
	.material{
		width: 750rpx;
		min-height: 930rpx;
		background-color: #FFFFFF;
		padding: 42rpx 29rpx 0rpx 30rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.iners{
		width: 750rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		padding: 0 37rpx;
		box-sizing: border-box;
		font-size: 24rpx;
	}
	.headerNumber {
		width: 750rpx;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 27rpx 0 30rpx;
		box-sizing: border-box;
		background-color: #FFFFFF;
	}
	
	.iner {
		width: 750rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 37rpx;
		box-sizing: border-box;
		font-size: 24rpx;
	}
	.container {
		width: 750rpx;
		height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #F8F8F8;
	}
	
	page {
		background-color: #F8F8F8;
	}
</style>